package com.zhang.controller;

import java.util.Arrays;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.lang.Result;
import com.zhang.entity.SysUserRole;
import com.zhang.entity.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhang.service.ITagService;

/**
 * 标签Controller
 *
 * @author zhang
 * @date 2022-10-11
 */
@RestController
@RequestMapping("/blog/tag")
public class TagController extends BaseController
{
    @Autowired
    private ITagService tagService;


    @GetMapping("/list")
    public Result list(Tag tag) {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        if (tag != null && tag.getTagName() != null &&
                tag.getTagName() != "") {
            queryWrapper.eq("tag_name", tag.getTagName());
        }
        Page<Tag> pageData = tagService.page(getPage(),queryWrapper);
        return Result.succ(pageData);
    }

    /**
     * 获取标签详细信息
     */
    @PreAuthorize("hasAuthority('blog:tag:query')")
    @GetMapping(value = "/{id}")
    public Result getInfo(@PathVariable("id") Long id)
    {
        return Result.succ(tagService.selectTagById(id));
    }

    /**
     * 新增标签
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('blog:tag:add')")
    public Result add(Tag tag)
    {
        return Result.succ(tagService.save(tag));
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('blog:tag:update')")
    public Result update(Tag tag) {
        return Result.succ(tagService.updateById(tag));
    }

    @Transactional
    @DeleteMapping("/delete")
    @PreAuthorize("hasAuthority('blog:tag:delete')")
    public Result delete(@RequestBody Long[] ids) {
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("id", ids));
        return Result.succ("");
    }

}
